package en.edu.zxj.rabbit.extensions.demo.listener;

import com.rabbitmq.client.Channel;
import en.edu.zxj.rabbit.extensions.demo.constant.Constants;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-21
 * @time: 16:41:43
 */
// @Component
public class DLXQueueListener {
    // @RabbitListener(queues = Constants.NORMAL_QUEUE_NAME)
    public void listenerNormalQueue(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.printf("正常队列 接收到消息: %s, deliverTag: %s\n", new String(message.getBody()), deliveryTag);
            // 模拟处理失败
            int num = 1 / 0;
            System.out.println("处理成功");
            // 手动确认
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("处理失败");
            // 拒绝消息
            // 第二个参数表示是否批量处理
            // 第三个参数表示是否requeue
            channel.basicNack(deliveryTag, true, false);
        }
    }

    @RabbitListener(queues = Constants.DLX_QUEUE_NAME)
    public void listenerDLXQueue(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.printf("%tc 死信队列接收到消息: %s, deliveryTag: %d%n",
                new Date(), new String(message.getBody(), StandardCharsets.UTF_8),
                message.getMessageProperties().getDeliveryTag());
        // 手动确认
        channel.basicAck(deliveryTag, true);
    }
}
